package com.soxing.braindata.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.soxing.braindata.common.config.RoleConfig;
import com.soxing.braindata.common.config.SystemConfig;
import com.soxing.braindata.common.util.WebHelper;
import com.soxing.braindata.dao.entity.*;
import com.soxing.braindata.dao.service.IResearchService;
import com.soxing.braindata.dao.service.IRoleService;
import com.soxing.braindata.dao.service.ISiteService;
import com.soxing.braindata.dao.service.IUserInfoExtService;
import com.soxing.braindata.domain.request.UserSearchRequest;
import com.soxing.braindata.domain.response.sync.SyncResponse;
import com.soxing.braindata.domain.rpc.OriginSite;
import com.soxing.braindata.domain.rpc.OriginUser;
import com.soxing.braindata.domain.vo.RoleInfoVo;
import com.soxing.braindata.domain.vo.UserInfoVo;
import com.soxing.braindata.domain.vo.UserVo;
import com.soxing.braindata.service.manager.IResearchManager;
import com.soxing.braindata.service.manager.ISiteManager;
import com.soxing.braindata.service.manager.IUserManager;
import com.soxing.braindata.service.sync.ISyncService;
import com.soxing.common.utils.response.MyPage;
import com.soxing.common.utils.response.WebResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.ehcache.core.util.CollectionUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.management.relation.RoleInfo;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/user")
@Api(value = "用户管理", tags = {"用户管理"})
public class UserController {

    @Resource
    private IUserManager userManager;

    @Resource
    private SystemConfig systemConfig; //调试的时候用一下

    @Resource
    private IResearchService researchService;

    @Resource
    private ISiteService siteService;

    @Resource
    private RoleConfig roleConfig;

    @Resource
    private ISyncService<OriginUser> syncUserService;

    @Resource
    private IRoleService roleService;

    @Resource
    private IUserInfoExtService userInfoExtService;

    @PostMapping
    @ApiOperation(value = "新增用户")
    public WebResponse<Boolean> add(@RequestBody OriginUser originUser) {
//        return userManager.add(userInfo);
        SyncResponse res = syncUserService.syncData(originUser);
        if (res.getCode() == 0 ) {
            return WebResponse.success("添加成功");
        }else {
            return WebResponse.fail("添加失败");
        }
    }

    /**
     * 更新用户
     *
     * @param userInfo
     * @return 返回操作结果 true:成功 false:失败
     */
    @PutMapping
    @ApiOperation(value = "更新用户")
    public WebResponse<Boolean> update(@RequestBody UserInfo userInfo) {
        if (userInfo.getId() == null) {
            return WebResponse.fail("主键ID为空");
        }
        return userManager.update(userInfo);
    }

    /**
     * 基于id获取用户信息
     *
     * @param id
     * @return 返回用户信息
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "基于id获取用户信息")
    public WebResponse<UserInfo> getById(@PathVariable("id") Integer id) {
        return userManager.getById(id);
    }

    /**
     * 获取登录用户的vo信息
     *
     * @return
     */
    @GetMapping("/getUserVo")
    @ApiOperation(value = "获取登录用户的vo信息")
    public WebResponse<UserVo> getUserVo() {

        if(systemConfig.isNeedLogin())
        {
            return WebResponse.success(WebHelper.getUserInfo());
        }
        else
        {
            System.out.println("无需登入，默认使用liuda测试");
            return WebResponse.success(userManager.getUserVo("zhangsan"));
        }
    }

    @GetMapping("/getUserExtByUserNum")
    @ApiOperation(value = "获取登录用户的ext信息")
    public WebResponse<UserInfoExt> getUserExtByUserNum(@RequestParam String userNum) {
        UserInfoExt userInfoExt = userInfoExtService.getOne(new LambdaQueryWrapper<UserInfoExt>().eq(UserInfoExt::getUserNum, userNum));
        return WebResponse.success(userInfoExt);
    }

    @GetMapping("/getUserVoByUserNum")
    @ApiOperation(value = "通过用户名获取用户信息")
    public WebResponse<UserInfoVo> getUserVoByUserNum(@RequestParam String userNum)
    {
        //以后加一个验证一下session 是否是系统管理员的代码，做一下权限的限制
        UserVo userVo = userManager.getUserVo(userNum);

        //下面这些代码的主要目的就是一次性查完这些 课题编码 中心编码的名字 返回名字给前端 而不是编码这样展示比较好
        List<UserInfoVo> userInfoList = new ArrayList<>();
        List<Role> roleList = userVo.getRoleList();

        Set<String> subjectPkIdSet = roleList.stream().map(role -> role.getSubjectPkId()).collect(Collectors.toSet());
        Set<String> sitePkIdSet = roleList.stream().map(role -> role.getSitePkId()).collect(Collectors.toSet());

        if(CollectionUtils.isEmpty(subjectPkIdSet))
        {
            return WebResponse.success();
        }

        List<Research> researchList = researchService.list(new LambdaQueryWrapper<Research>().in(Research::getSubjectPkId, subjectPkIdSet));
        List<Site> siteList = siteService.list(new LambdaQueryWrapper<Site>().in(Site::getSitePkId, sitePkIdSet));

        Map<String, List<Research>> researchMap = researchList.stream().collect(Collectors.groupingBy(Research::getSubjectPkId));
        //Map<String, String> siteMap = siteList.stream().collect(Collectors.toMap(Site::getSitePkId, Site::getSiteName));
        Map<String, List<Site>> siteMap = siteList.stream().collect(Collectors.groupingBy(Site::getSitePkId));

        UserInfoVo userInfoVo = new UserInfoVo();
        List<RoleInfoVo> roleInfoList = new ArrayList<>();
        roleList.forEach(
                item->{
                    RoleInfoVo roleInfoVo = new RoleInfoVo();
                    roleInfoVo.setRoleName(roleConfig.getRoleName(item.getRolePkId()));
                    roleInfoVo.setRolePkId(item.getRolePkId());
                    roleInfoVo.setId(item.getId());
                    //roleInfoVo.setSiteName(siteMap.get(item.getSitePkId()));
                    if(researchList.size() > 0){
                        roleInfoVo.setResearchName(researchMap.get(item.getSubjectPkId()).get(0).getResearchName());
                        roleInfoVo.setSubjectCode(researchMap.get(item.getSubjectPkId()).get(0).getSubjectCode());
                    }
                    if(siteList.size() > 0){
                        roleInfoVo.setSiteName(siteMap.get(item.getSitePkId()).get(0).getSiteName());
                        roleInfoVo.setSiteCode(siteMap.get(item.getSitePkId()).get(0).getSiteCode());
                    }
                    roleInfoList.add(roleInfoVo);
                }
        );
        userInfoVo.setRoleInfoList(roleInfoList);
        return WebResponse.success(userInfoVo);
    }

    @PostMapping("/addRole")
    @ApiOperation(value = "添加权限")
    public WebResponse<Boolean> addRole(@RequestBody Role role) {
        Boolean res = roleService.save(role);
        if (res) {
            return WebResponse.success("添加成功");
        }else {
            return WebResponse.fail("添加失败");
        }
    }

    @PostMapping("/deleteRole/{id}")
    @ApiOperation(value = "删除权限")
    public WebResponse<Boolean> deleteRole(@PathVariable("id") Integer id) {
        Boolean res = roleService.removeById(id);
        if (res) {
            return WebResponse.success("删除成功");
        } else {
            return WebResponse.fail("删除失败");
        }
    }

    /**
     * 基于用户pin获取用户信息
     *
     * @param pin
     * @return 返回用户信息
     */
    @GetMapping("/getByPin/{pin}")
    @ApiOperation(value = "基于用户pin获取用户信息")
    public WebResponse<UserInfo> getByPin(@PathVariable("pin") String pin) {
        return userManager.getByPin(pin);
    }

    /**
     * 基于id删除用户记录
     *
     * @param id 主键ID
     * @return 返回操作结果 true:成功 false:失败
     */
    @PostMapping("/delete/{id}")
    @ApiOperation(value = "基于id删除用户记录")
    public WebResponse<Boolean> deleteById(@PathVariable("id") Integer id) {
        return userManager.deleteById(id);
    }

    /**
     * 基于条件查询用户
     *
     * @param userSearchRequest
     * @return
     */
    @PostMapping("/search")
    @ApiOperation(value = "基于条件查询用户")
    public WebResponse<MyPage<UserInfo>> search(@RequestBody(required = false) UserSearchRequest userSearchRequest) {
        if (userSearchRequest == null) {
            userSearchRequest = new UserSearchRequest();
        }
        return userManager.search(userSearchRequest);
    }


}
